package com.sztz.excel;

import com.alibaba.excel.write.style.row.AbstractRowHeightStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

import java.util.Iterator;


/**
 * 导出EasyExcel自适应高度策略
 * @author yzy
 * @date 2022/8/2 17:08
 */
public class AutoCellHeightStrategy extends AbstractRowHeightStyleStrategy {
    /**
     * 默认高度
     */
    private static final Integer DEFAULT_HEIGHT = 255;
    @Override
    protected void setHeadColumnHeight(Row row, int relativeRowIndex) {}

    @Override
    protected void setContentColumnHeight(Row row, int relativeRowIndex) {
        Iterator<Cell> cellIterator = row.cellIterator();
        if (!cellIterator.hasNext()) {
            return;
        }
        // 默认为 1行高度
        Integer maxHeight = 1;
        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();
            switch (cell.getCellTypeEnum()) {
                case STRING:
                    maxHeight = Math.max(maxHeight, cell.getStringCellValue().getBytes().length);
                    break;
                default:
                    break;
            }
        }
        row.setHeight((short) (maxHeight * DEFAULT_HEIGHT));
    }
}
